﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using Microsoft.Phone.Controls;

namespace Chenglin.WPTelecodeTable
{
    public partial class MainPage : PhoneApplicationPage
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public MainPage()
        {
            InitializeComponent();

            // Hook event handlers
            this.InputTextBox.TextChanged += InputTextBox_TextChanged;
        }

        private void InputTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            // clear the existing text first
            OutputTextBlock.Text = string.Empty;

            var charCodeMap = App.CharCodeMap;
            string text = InputTextBox.Text;
            if (!string.IsNullOrWhiteSpace(text))
            {
                int pos = 0;
                while (pos < text.Length)
                {
                    char ch = text[pos];
                    string code;

                    StringBuilder sb = new StringBuilder();
                    Run textRun = new Run();

                    if (charCodeMap.TryGetValue(ch, out code))
                    {
                        // For the characters which have defined mappings.
                        sb.Append(code);

                        while ((++pos) < text.Length && charCodeMap.TryGetValue(text[pos], out code))
                        {
                            sb.Append(' ');
                            sb.Append(code);
                        }
                    }
                    else
                    {
                        // For the characters which don't have mappings 
                        sb.Append(ch);
                        while ((++pos) < text.Length && !charCodeMap.ContainsKey(text[pos]))
                        {
                            sb.Append(text[pos]);
                        }

                        // Highlight the characters
                        textRun.Foreground = (Brush)Application.Current.Resources["PhoneAccentBrush"];
                    }

                    textRun.Text = sb.ToString();
                    OutputTextBlock.Inlines.Add(textRun);
                }
            }
        }
    }
}